package com.topone.Utils;

import com.topone.Const.Model;
import com.topone.dataObject.CouponCode;
import com.topone.service.CouponCodeService;
import lombok.Data;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/12/28,0028.
 */
@Data
@Service
@Slf4j
public  class CodeUntil {
    @Autowired
    private  CouponCodeService couponCodeService;

    public static String getBussinessCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");//设置日期格式
        Random random=new Random();
        int s=random.nextInt(1000)%(1000-100+1) + 100;
        String code="FZ"+df.format(new Date())+s;
        return code;
    }

    public static String getTcCouponCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");//设置优惠券日期格式
        Random random=new Random();
        int s=random.nextInt(1000)%(1000-100+1) + 100;
        String code="C"+df.format(new Date())+s;
        return code;
    }

   @Transactional
   @Synchronized
   public  String getCouponCode(){
       List<CouponCode> couponCodes= couponCodeService.findOne(
               Model.COUPONCODE_INITAL_STATUS);
       String code=null;
       if(couponCodes.size()>0 && Objects.nonNull(couponCodes.get(0))) {
           log.debug(code);
            code = couponCodes.get(0).getCode();
            updateCouponStatusOnUnuse(code, Model.COUPONCODE_UNUSE);
       }
       log.debug(code);
          return code;
    }
    public  String updateCouponStatus(String code,Integer status) {
        if (StringUtils.isNotEmpty(code)) {
            CouponCode couponCode = couponCodeService.findByCode(code);
            if (Objects.nonNull(couponCode) && (couponCode.getStatus() == Model.COUPONCODE_UNUSE)) {
                couponCode.setStatus(status);
                couponCodeService.update(couponCode);
                return "success";
            } else {
                return null;
            }
        }else{
            return null;
        }
    }
    public  String updateCouponStatusOnUnuse(String code,Integer status) {
        if (StringUtils.isNotEmpty(code)) {
            CouponCode couponCode = couponCodeService.findByCode(code);
            if (Objects.nonNull(couponCode) && (couponCode.getStatus() == Model.COUPONCODE_INITAL_STATUS)) {
                couponCode.setStatus(status);
                couponCodeService.update(couponCode);
                return "success";
            } else {
                return null;
            }
        }else{
            return null;
        }
    }
}
